<template>
  <basic-dialog
    title="关联弹框"
    width="65%"
    :visible="dialogVisible"
    :show-close="false"
  >
    <basic-table-form
      ref="tableForm"
      isBtnBarSingleRow
      :formColumns="formInfo.itemList"
      :dataSource="formInfo.dataSource"
      :handleClearForm="formResetFn"
      :handleSearchForm="formQueryFn"
      @getFormData="getFormDataFn"
    >
      <template slot="extensionActions">
        <template v-if="tabs.current === tabs.nameList[0]">
          <el-button type="primary" @click="handleBatchAssociate">批量关联</el-button>
        </template>
        <template v-else>
          <el-button @click="handleBatchCancel">批量取消</el-button>
        </template>
      </template>
    </basic-table-form>
    <el-tabs
      v-model="tabs.current"
      @tab-click="handleSwitchTabs"
    >
      <el-tab-pane
        label="未关联"
        :name="tabs.nameList[0]"
      >
      </el-tab-pane>
      <el-tab-pane
        label="已关联"
        :name="tabs.nameList[1]"
      >
      </el-tab-pane>
    </el-tabs>
    <skus-table
      showActionCol
      showSelectCol
      showPagination
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      :total="pagination.total"
      :actionRender="renderActionBtnFn"
      :selectionChange="handleSelectionChange"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    />
    <el-row slot="ft" type="flex" justify="center">
      <el-button type="primary" @click="handleReturnPreviousPage">返回表单</el-button>
    </el-row>
  </basic-dialog>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapState, mapMutations } from 'vuex';
import BasicDialog from '@/components/BasicDialog';
import BasicTableForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import { isResponseSuccess } from '@/utils/bizUtils';
export default {
  props: {
    /* 关联弹框显隐开关 */
    visible: {
      type: Boolean,
      default: false
    },
    /* 关联弹框表单item列集合 */
    formInfo: {
      type: Object,
      required: true
    },
    /* 关联弹框表格columns */
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    /* 关联弹框维度key值, 默认uuid */
    dimensionKey: {
      type: String,
      default: 'uuid'
    },
    /* 关联返回表格数据接口请求key */
    returnTableKey: {
      type: String,
      default: 'uuid'
    },
    /* 请求查询数据接口区别未关联和已关联的入参 */
    distinctParams: {
      type: Object
    },
    /* 查询接口及类型 */
    requestApi: {
      type: Object,
      required: true
    },
    /* 表单是否可以为空查询 */
    emptyFormIsQuery: {
      type: Boolean,
      default: false
    },
    /* 返回表单是否清空form表单数据 */
    closeRestFormFlag: {
      type: Boolean,
      default: true
    },
  },
  components: {
    BasicDialog,
    BasicTableForm,
    SkusTable
  },
  data () {
    return {
      dialogVisible: false,
      tabs: {
        current: 'notAssociated', // 当前tabs页签
        nameList: ['notAssociated', 'hasAssociated'] // tabs页签key集合
      },
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 50, // 每页条数
        total: 0 // 总条数
      },
      dataSource: [], // 表格数据
      selectionList: [], // 已勾选的表格数据集合
      formData: {}, // 表单数据
      globalLoading: null,
    }
  },
  destroyed () {
    this.CLEAR_GOODS();
  },
  watch: {
    visible (val) {
      this.dialogVisible = val;
    }
  },
  computed: {
    ...mapState('commonComps/basicAssociatedDialog', [
      'associatedRowList'
    ])
  },
  methods: {
    ...mapMutations('commonComps/basicAssociatedDialog', [
      'ASSOCIATED_GOODS', 'CANCEL_GOODS', 'CLEAR_GOODS'
    ]),
    /* 操作栏按钮渲染方法 */
    renderActionBtnFn (h, { row, index }) {
      let btnLabel = '关联';
      let calledFn = this.handleAssociateGoods;
      if (this.tabs.current === this.tabs.nameList[1]) {
        btnLabel = '取消';
        calledFn = this.handleCancelGoods;
      }
      return (<div class="table-action">
        {<el-button
          size="mini"
          type="text"
          onClick={() => calledFn(row, index)}
        >{ btnLabel }
        </el-button>}
      </div>);
    },
    /* 验证表单数据是否都为空的方法 */
    judgeEmptyFormFn () {
      const list = Object.values(this.formData).filter(item => {
        if (item) { return true; }
      });
      if (list.length === 0 && this.tabs.current === this.tabs.nameList[0]) {
        return true;
      }
      return false;
    },
    /* 表单清空方法 */
    formResetFn () {
      if (this.tabs.current === this.tabs.nameList[0]) {
        this.clearTableDataFn();
        return false;
      }
      this.formQueryFn();
    },
    /* 表单查询方法 */
    formQueryFn () {
      this.pagination.pageNum = 1; // 每次切换tabs，都重置当前页为第一页
      this.handleGetTableData();
    },
    /* 获取表单数据方法 */
    getFormDataFn (source) {
      this.formData = source;
    },
    /* 加载表格数据事件 */
    handleGetTableData () {
      /* 如果表单查询检索条件不许为空时，校验表单是否为空 */
      if (!this.emptyFormIsQuery && this.judgeEmptyFormFn()) {
        this.clearTableDataFn();
        return this.$message.warning('请输入搜索条件后进行关联');
      }
      /* 获取map集合聚合后的已关联商品集合 */
      let associatedUuids = [];
      this.associatedRowList.forEach(item => {
        associatedUuids.push(item[this.returnTableKey]);
      });
      /* 已关联没有关联数据的时候不查询接口 */
      if (associatedUuids.length === 0 && this.tabs.current === this.tabs.nameList[1]) {
        this.dataSource = [];
        this.pagination.total = 0;
        return false;
      }
      /* otherParams 关联接口区分未关联和已关联的入参 */
      let otherParams = {};
      if (this.tabs.current === this.tabs.nameList[0]) {
        otherParams[this.distinctParams.notAssociated] = associatedUuids;
      }
      if (this.tabs.current === this.tabs.nameList[1]) {
        otherParams[this.distinctParams.associated] = associatedUuids;
      }
      let { pageNum, pageSize } = this.pagination;
      let data = {
        ...this.formData,
        nowPage: pageNum,
        pageShow: pageSize,
        ...otherParams
      };
      this.getTableDataAction(data).then(result => {
        if (!result) {
          this.dataSource = [];
          this.pagination.total = 0;
          return false;
        }
        this.dataSource = result.results;
        this.pagination.total = result.totalNum;
      })
    },
    /* 获取表格数据action */
    async getTableDataAction (data) {
      const { url, type } = this.requestApi;
      const curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      try {
        this.globalLoading = this.$loading({ target: '.el-dialog__body' });
        const res = await ApiRequest(url, type, data);
        this.globalLoading.close();
        if (!isResponseSuccess(res)) {
          return false;
        }
        return res.retData;
      } catch (err) {
        this.globalLoading.close();
      }
    },
    /* 切换tabs事件 */
    handleSwitchTabs () {
      this.formQueryFn();
    },
    /* 清空弹框状态 */
    clearInfoStatusFn () {
      if (this.closeRestFormFlag) {
        this.formResetFn(); // 重置表单搜索条件
      }
      this.tabs.current = this.tabs.nameList[0]; // 重置关联tab状态
      this.clearTableDataFn();
    },
    /* 清空表格数据 */
    clearTableDataFn () {
      this.pagination = { // 重置分页状态
        pageNum: 1, // 当前页码
        pageSize: 50, // 每页条数
        total: 0 // 总条数
      }
      this.dataSource = []; // 重置表格数据
    },
    /* 批量关联事件 */
    handleBatchAssociate () {
      this.batchOptionsFn(this.ASSOCIATED_GOODS);
    },
    /* 批量取消事件 */
    handleBatchCancel () {
      this.batchOptionsFn(this.CANCEL_GOODS);
    },
    /* 批量操作方法 */
    batchOptionsFn (calledFn) {
      if (this.selectionList.length === 0) {
        return this.$message.warning('请勾选商品');
      }
      this.selectionList.forEach((value) => {
        calledFn({ row: value, type: this.dimensionKey });
      });
      /* 当当前页勾选数量等于当前页面表格数量，且不为第一页时，页码减一 */
      if (this.selectionList.length === this.dataSource.length && this.pagination.pageNum > 1) {
        this.pagination.pageNum -= 1;
      }
      this.handleGetTableData();
    },
    /* 关联事件 */
    handleAssociateGoods (row, index) {
      this.singleOptionsFn(row, this.ASSOCIATED_GOODS);
    },
    /* 取消事件 */
    handleCancelGoods (row, index) {
      this.singleOptionsFn(row, this.CANCEL_GOODS);
    },
    /* 单个操作方法 */
    singleOptionsFn (row, calledFn) {
      calledFn({ row, type: this.dimensionKey });
      /* 当当前页仅剩一条数据，且不为第一页时，页码减一 */
      if (this.dataSource.length === 1 && this.pagination.pageNum > 1) {
        this.pagination.pageNum -= 1;
      }
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 表格数据勾选或勾选取消方法 */
    handleSelectionChange (list) {
      this.selectionList = list;
    },
    /* 改变页码事件 */
    handlePageChange (currentPage) {
      this.pagination.pageNum = currentPage;
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 改变当前页条数大小事件 */
    handlePageSizeChange (pageSize) {
      this.pagination.pageSize = pageSize;
      if (this.dataSource.length === 0) {
        return false;
      }
      this.handleGetTableData(); // 重新加载表格数据
    },
    /* 返回表单事件 */
    handleReturnPreviousPage () {
      this.$emit('update:visible', false);
      this.$emit('handleSubmit');
      this.clearInfoStatusFn();
    },
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-dialog__body {
  padding-bottom: 0px;
}
/deep/ .el-dialog__footer {
  padding: 10px;
}
/deep/ .table_form_wrap {
  margin-bottom: 0px;
}
/deep/ .pagination-container {
  margin-top: 10px;
}
</style>
